package models;

import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;

import play.data.validation.Required;
import play.db.jpa.Model;

@Entity
public class PurchasedOrder extends Model {

	@ManyToOne
	public User customer;

	@OneToOne
	public ShoppingCart billedShoppingCart;

	@Required
	@Enumerated(EnumType.STRING)
	public PaymentMethod paymentMethod;

	@Required
	@Enumerated(EnumType.STRING)
	public DeliveryOption deliveryOption;

	public PurchasedOrder(User customer, ShoppingCart shoppingCart, 
			PaymentMethod paymentMethod, DeliveryOption deliveryOption) {
		customer.currentShoppingCart = null;
		customer.save();
		this.customer = customer;
		shoppingCart.isBilled = true;

		for (ShoppingCartLine line : shoppingCart.lines) {
			Product product = line.product;
			if (product instanceof Salad) {
				Salad salad = (Salad) line.product;
				if (salad != null){
					salad.popularity++;
					salad.save();
				}
			}
		}

		shoppingCart.save();
		this.billedShoppingCart = shoppingCart;
		this.paymentMethod = paymentMethod;
		this.deliveryOption = deliveryOption;
	}

	public double getPrice() {
		// discount of 10% if pick-up
		if (this.deliveryOption == DeliveryOption.PICK_UP) {
			return this.billedShoppingCart.getPrice() * 0.9;
		}
		return this.billedShoppingCart.getPrice();
	}

}
